package logic;
import java.net.DatagramPacket;


public class ThreadMDR extends Thread{

	private Server server;
	public ThreadMDR(Server server)
	{
		this.setServer(server);
	}
	public void run()
	{
		byte[] receiveData = new byte[65000];

		DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

		while(true){
			try {
				server.getMDR_socket().receive(receivePacket);
				String message_received = new String( receivePacket.getData(),0,receivePacket.getLength());
				String[] chunkParts=new String[10];
				int indexFinalHeader = message_received.indexOf("\r\n\r\n");
				if(indexFinalHeader == -1)
				{
					System.out.println(message_received);
					System.out.println(receivePacket.getAddress().toString());
				}
				else if(indexFinalHeader != -1)
				{
					String header = message_received.substring(0, indexFinalHeader);
					chunkParts=header.split(" ");
					String version=chunkParts[1];

					if(chunkParts[0].equals("CHUNK") && server.getDefautVersion().equals(version) )
					{
						LogMensage lm=new LogMensage("RECEIVED CHUNK - HOST: " + receivePacket.getAddress().getHostName()+ " FileID: "+chunkParts[2] + " Chunk number: "+ chunkParts[3]);

						Server.logMensagesStr.insertElementAt(lm.str(), 0);
						int contentStart=message_received.indexOf("\r\n\r\n")+4;
						if(indexFinalHeader == -1)
						{
							System.out.println(receivePacket.getAddress().toString());
						}
						else if(indexFinalHeader != -1)
						{
							byte[] cont=new byte[receivePacket.getLength()-(contentStart)];
							for(int i=0;i<receivePacket.getLength()-contentStart;i++)
							{
								cont[i]=receiveData[contentStart+i];
							}
							ChunkMessage ch = new ChunkMessage(chunkParts[2], Integer.parseInt(chunkParts[3]), cont, version);
							server.getChunkMessage().add(ch);
						}
					}


				}
			}catch (Exception  e) {

				//e.printStackTrace();
			}
		}
	}
	public Server getServer() {
		return server;
	}
	public void setServer(Server server) {
		this.server = server;
	}
}
